package com.agricultural.machine.path;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 路径优化器类
 */
public class PathOptimizer {
    private static PathOptimizer instance;
    private final PathStrategyFactory strategyFactory;
    private String currentStrategyName;
    private final Map<String, List<PathPoint>> machinePaths;
    
    private PathOptimizer() {
        this.strategyFactory = PathStrategyFactory.getInstance();
        this.currentStrategyName = "direct";
        this.machinePaths = new HashMap<>();
    }
    
    public static synchronized PathOptimizer getInstance() {
        if (instance == null) {
            instance = new PathOptimizer();
        }
        return instance;
    }
    
    /**
     * 设置路径策略
     */
    public void setPathStrategy(String strategyName) {
        if (!strategyName.equals(currentStrategyName)) {
            // 记录策略变更前后的信息
            String oldStrategy = currentStrategyName;
            // 验证策略是否存在
            strategyFactory.getStrategy(strategyName);
            this.currentStrategyName = strategyName;
            
            // 添加更明显的日志
            System.out.println("\n【策略变更通知】");
            System.out.println("路径策略已从 [" + oldStrategy + "] 切换为 [" + strategyName + "]");
            System.out.println("触发时间: " + java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            // 尝试获取调用栈信息，找出谁触发了策略变更
            StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
            if (stackTraceElements.length > 3) {
                String caller = stackTraceElements[3].getClassName();
                if (caller.contains("AbstractMachine")) {
                    System.out.println("触发者: 农机自动响应系统 (环境变化)");
                } else if (caller.contains("ObstacleHandler")) {
                    System.out.println("触发者: 安全处理系统 (障碍物事件)");
                } else if (caller.contains("AgriculturalSystem")) {
                    System.out.println("触发者: 用户手动设置");
                } else {
                    System.out.println("触发者: " + caller);
                }
            }
            System.out.println("-----------------------------------");
        }
    }
    
    /**
     * 获取当前路径策略
     */
    public PathStrategy getCurrentPathStrategy() {
        return strategyFactory.getStrategy(currentStrategyName);
    }
    
    /**
     * 优化路径
     */
    public List<PathPoint> optimizePath(String machineId, List<PathPoint> originalPath, 
                                       TerrainData terrain, List<PathPoint> otherMachinePaths) {
        System.out.println("开始优化农机 " + machineId + " 的路径...");
        
        // 获取起点和终点
        PathPoint start = originalPath.get(0);
        PathPoint end = originalPath.get(originalPath.size() - 1);
        
        // 使用当前策略计算路径
        List<PathPoint> optimizedPath = getCurrentPathStrategy().calculatePath(start, end, terrain);
        
        // 保存路径
        machinePaths.put(machineId, new ArrayList<>(optimizedPath));
        
        return optimizedPath;
    }
    
    /**
     * 获取农机的优化路径
     */
    public List<PathPoint> getOptimizedPath(String machineId) {
        return machinePaths.getOrDefault(machineId, new ArrayList<>());
    }
    
    /**
     * 检查路径冲突
     */
    public boolean checkPathConflict(List<PathPoint> path1, List<PathPoint> path2, double safeDistance) {
        // 简单实现：检查每个点之间的距离
        for (PathPoint p1 : path1) {
            for (PathPoint p2 : path2) {
                double distance = Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
                if (distance < safeDistance) {
                    return true;
                }
            }
        }
        return false;
    }
} 